# -*- coding: utf-8 -*-
"""
Created on  10:21:08 2021

@author: XiaoChen Fu
"""

from flask import Flask
from flask_restful import reqparse,abort,Api,Resource
import traceback,time,os
from scan import Scan
from api.interface_appear_papper import interfaceAppearPapper

app = Flask(__name__)
api = Api(app)

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '哈哈哈'},
    'todo3': {'task': 'profit!'},
}

parser = reqparse.RequestParser()
parser.add_argument('task')

scan = Scan()

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]

    def delete(self, todo_id):
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201

class Recong(Resource):
    def get(self):
        try:
            files = os.listdir('image')
            for file in files:
                if 'jpg' in file:
                    print(file)
                    start_time = time.time()
                    pre_img = scan.pre_deal_image(r'image/'+file)
                    elph_pre = time.time() - start_time

                    start_time = time.time()
                    opt_cnt,opt_dir = scan.pick_roi(pre_img)
                    print('图像预处理耗时：', elph_pre)
                    print('提取内容耗时：', (time.time() - start_time))
                    # if opt_cnt == 37:
            return '识别完成'
        except Exception as e:
            print(traceback.print_exc())
            return str(e)
        return '识别失败'

# 设置路由
# api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
api.add_resource(Recong,'/recong/start')
api.add_resource(interfaceAppearPapper,'/api/recong/list/<id>')

if __name__ == '__main__':
    app.run(debug=True)